package logger

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
	"time"
)

// EbbFlowLogger EbbFlow集成日志器
type EbbFlowLogger struct {
	nodeID     int
	perfLogger *PerformanceLogger
	awsDeployer *AWSDeployer
	logDir     string
}

// NewEbbFlowLogger 创建EbbFlow日志器
func NewEbbFlowLogger(nodeID int, logDir string) (*EbbFlowLogger, error) {
	// 创建性能日志记录器
	perfLogger, err := NewPerformanceLogger(nodeID, logDir, 30*time.Second)
	if err != nil {
		return nil, fmt.Errorf("failed to create performance logger: %v", err)
	}

	// 创建AWS部署器
	configPath := filepath.Join(logDir, "aws_config.yaml")
	awsDeployer, err := NewAWSDeployer(configPath, logDir)
	if err != nil {
		// 如果配置文件不存在，创建一个默认的
		awsDeployer = &AWSDeployer{logDir: logDir}
		awsDeployer.CreateConfigFile()
		awsDeployer, _ = NewAWSDeployer(configPath, logDir)
	}

	return &EbbFlowLogger{
		nodeID:     nodeID,
		perfLogger: perfLogger,
		awsDeployer: awsDeployer,
		logDir:     logDir,
	}, nil
}

// LogPerformance 记录性能指标
func (el *EbbFlowLogger) LogPerformance(tps float64, latency int64, epoch int, batchSize int, txSize int) {
	el.perfLogger.RecordMetrics(tps, latency, epoch, batchSize, txSize)
}

// GenerateAWSDeployment 生成AWS部署脚本
func (el *EbbFlowLogger) GenerateAWSDeployment(scenario string) error {
	return el.awsDeployer.GenerateDeploymentScript(scenario)
}

// GenerateAWSTest 生成AWS测试脚本
func (el *EbbFlowLogger) GenerateAWSTest(scenario string) error {
	return el.awsDeployer.GenerateTestScript(scenario)
}

// Stop 停止日志记录器
func (el *EbbFlowLogger) Stop() {
	el.perfLogger.Stop()
	
	// 导出指标
	if err := el.perfLogger.ExportMetrics(); err != nil {
		log.Printf("Failed to export metrics: %v", err)
	}
}

// GetMetrics 获取性能指标
func (el *EbbFlowLogger) GetMetrics() []PerformanceMetrics {
	return el.perfLogger.GetMetrics()
}

// CreateAWSSetup 创建AWS设置
func (el *EbbFlowLogger) CreateAWSSetup() error {
	// 创建配置文件
	if err := el.awsDeployer.CreateConfigFile(); err != nil {
		return fmt.Errorf("failed to create config file: %v", err)
	}

	// 生成部署脚本
	scenarios := []string{"small_cluster", "medium_cluster", "large_cluster", "stress_test"}
	for _, scenario := range scenarios {
		if err := el.GenerateAWSDeployment(scenario); err != nil {
			log.Printf("Failed to generate deployment script for %s: %v", scenario, err)
		}
		if err := el.GenerateAWSTest(scenario); err != nil {
			log.Printf("Failed to generate test script for %s: %v", scenario, err)
		}
	}

	// 创建README文件
	readmePath := filepath.Join(el.logDir, "README.md")
	readme := "# EbbFlow AWS Deployment\n\n" +
		"## 概述\n" +
		"这个目录包含了EbbFlow在AWS上的部署和测试脚本。\n\n" +
		"## 文件说明\n" +
		"- aws_config.yaml: AWS配置信息\n" +
		"- deploy_aws.sh: AWS部署脚本\n" +
		"- test_aws.sh: AWS测试脚本\n" +
		"- node_*_performance.log: 节点性能日志\n" +
		"- node_*_metrics.json: 节点指标数据\n\n" +
		"## 使用方法\n\n" +
		"### 1. 配置AWS\n" +
		"```bash\n" +
		"# 配置AWS CLI\n" +
		"aws configure\n\n" +
		"# 创建密钥对\n" +
		"aws ec2 create-key-pair --key-name ebbflow-aws-key --query 'KeyMaterial' --output text > ~/.ssh/ebbflow-key.pem\n" +
		"chmod 400 ~/.ssh/ebbflow-key.pem\n" +
		"```\n\n" +
		"### 2. 部署集群\n" +
		"```bash\n" +
		"# 部署小型集群\n" +
		"./deploy_aws.sh\n\n" +
		"# 运行测试\n" +
		"./test_aws.sh\n" +
		"```\n\n" +
		"### 3. 监控性能\n" +
		"性能日志会每30秒记录一次，包含：\n" +
		"- TPS (每秒事务数)\n" +
		"- 延迟 (毫秒)\n" +
		"- Epoch (轮次)\n" +
		"- 批次大小\n" +
		"- 交易大小\n" +
		"- 内存使用\n" +
		"- CPU使用率\n\n" +
		"## 测试场景\n" +
		"- small_cluster: 4节点, t3.medium, 30秒\n" +
		"- medium_cluster: 7节点, t3.large, 60秒\n" +
		"- large_cluster: 16节点, t3.xlarge, 120秒\n" +
		"- stress_test: 32节点, t3.2xlarge, 300秒\n"

	if err := os.WriteFile(readmePath, []byte(readme), 0644); err != nil {
		return fmt.Errorf("failed to create README: %v", err)
	}

	fmt.Printf("AWS setup created in: %s\n", el.logDir)
	return nil
}
